package com.zhou.bjgl.bjgl.util;


import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.zhou.bjgl.bjgl.req.b_file_upload.BFileUploadQueryReq;
import io.minio.*;
import io.minio.errors.*;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;


import java.io.*;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

/**
 * @description： minio工具类
 * @author：jz
 * @date：2021/8/25 10:03
 */
@Component
public class MinioUtil {

   /* @Value("${minio.bucketName}")
    private String bucketName;*/


    private final static String MY_PROFILE_BUCKET="myprofile";

    @Autowired
    private MinioClient minioClient;

    /**
     * description: 判断bucket是否存在，不存在则创建
     *
     * @return: void
     * @author: jz
     * @time: 2021/8/25 10:20
     */
    public void existBucket(String name) {
        try {
            boolean exists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(name).build());
            if (!exists) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(name).build());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * description: 根据BFileUploadQueryReq上传文件
     *
     * @return: java.lang.String
     * @author: jz
     * @time: 2021/8/25 10:44
     */
    public void upload(MultipartFile file, BFileUploadQueryReq req) {
        InputStream in = null;
        try {
            in = file.getInputStream();
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(req.getFolder())
                    .object(req.getFileNameInMinio())
                    .stream(in, in.available(), -1)
                    .contentType(file.getContentType())
                    .build()
            );
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    /**
     * description: 上传文件
     *
     * @return: java.lang.String
     * @author: jz
     * @time: 2021/8/25 10:44
     */
    public void uploadFile(MultipartFile file, String nameInMinio) {
        InputStream in = null;
        try {
            in = file.getInputStream();
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(MY_PROFILE_BUCKET)
                    .object(nameInMinio)
                    .stream(in, in.available(), -1)
                    .contentType(file.getContentType())
                    .build()
            );
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    /**
     * description: 下载文件
     *
     * @return: org.springframework.http.ResponseEntity<byte [ ]>
     * @author: jz
     * @time: 2021/8/25 10:34
     */
    public ResponseEntity<byte[]> download(String nameInMinion, String bucket, String originFilename) {
        ResponseEntity<byte[]> responseEntity = null;
        InputStream in = null;
        ByteArrayOutputStream out = null;
        try {
            in = minioClient.getObject(GetObjectArgs.builder().bucket(bucket).object(nameInMinion).build());
            out = new ByteArrayOutputStream();
            IOUtils.copy(in, out);
            //封装返回值
            byte[] bytes = out.toByteArray();
            HttpHeaders headers = new HttpHeaders();
            try {
                //用encode进行UTF-8解决中文乱码问题
                headers.add("Content-Disposition", "attachment;filename=" + URLEncoder.encode(originFilename, Constants.UTF_8));
/*                headers.add("Content-Disposition", "attachment;filename=" + originFilename);*/
            } catch (Exception e) {
                e.printStackTrace();
            }
            headers.setContentLength(bytes.length);
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setAccessControlExposeHeaders(Arrays.asList("*"));
            responseEntity = new ResponseEntity<byte[]>(bytes, headers, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return responseEntity;
    }

    /**
     * description: 获取文件流
     *
     * @return: org.springframework.http.ResponseEntity<byte [ ]>
     * @author: weirx
     * @time: 2021/8/25 10:34
     */
    public InputStream downloadForFile(String nameInMinion, String bucket, String originFilename) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        ResponseEntity<byte[]> responseEntity = null;
        InputStream in = null;
        ByteArrayOutputStream out = null;

        in = minioClient.getObject(GetObjectArgs.builder().bucket(bucket).object(nameInMinion).build());


        return in;


    }

    /**
     * 删除桶中指定的文件对象
     * @param bucketName
     * @param fileName
     * @throws Exception
     */
    public void removeFile(String bucketName, String fileName) throws Exception {
        minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(fileName).build());
    }

    public void removeFolder(String bucketName) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        minioClient.removeBucket(RemoveBucketArgs.builder().bucket(bucketName).build());
    }
}
